<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SSE Example</title>
</head>
<body>
    <h1>实时流式输出</h1>
    <div id="output" style="white-space: pre-wrap;"></div>

    <script>
        // 创建 EventSource 实例，连接到服务器的 SSE 端点
        const eventSource = new EventSource('http://127.0.0.1:5000/stream');

        // 监听服务器发送的消息
        eventSource.onmessage = function(event) {
            //console.log('Received message:', event.data);
            if (event.data === '[DONE]') {
                console.log('Stream ended');
                eventSource.close();  // 关闭连接
            } else {
                // 将接收到的数据追加到页面上
                //document.getElementById('output').textContent += event.data + '\n';
                document.getElementById('output').textContent += event.data;
                // 处理接收到的数据
            }
        };

        // 监听自定义事件（如果需要）
      /*  eventSource.addEventListener('customEvent', function(event) {
            console.log('Custom event data:', event.data);
           // eventSource.close();
        });*/

        // 处理错误
        eventSource.onerror = function(event) {
            console.error('EventSource failed:', event);
            eventSource.close();

        };
    </script>
</body>
</html>